package com.lap.auth.application.dict.assembler;

import com.lap.auth.application.dict.command.CreateDictTypeCmd;
import com.lap.auth.domain.dict.Dict;
import com.lap.auth.domain.dict.DictType;
import com.lap.framework.enums.YesNo;
import com.lap.i18n.starter.helper.LangHelper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Mapper(componentModel = "spring")
public interface DictTypeAssembler {
  Logger log = LoggerFactory.getLogger(DictTypeAssembler.class);
  String COLON = ":";
  String REGULAR = "[;,；，:：]";
  String TEST = "[-=]";

  @Mapping(target = "createTime", ignore = true)
  @Mapping(target = "createdBy", ignore = true)
  @Mapping(target = "updateTime", ignore = true)
  @Mapping(target = "updatedBy", ignore = true)
  @Mapping(target = "event", ignore = true)
  @Mapping(target = "id", ignore = true)
  @Mapping(target = "dictList", expression = "java(fromParam(cmd.getCode(),cmd.getRemark()))")
  DictType toDomain(CreateDictTypeCmd cmd);

  default List<Dict> fromParam(String dictTypeCode, String param) {
    if (StringUtils.isBlank(param)) return Collections.emptyList();
    return param.contains(COLON)
        ? parseColonMode(dictTypeCode, param)
        : parseNormalMode(dictTypeCode, param);
  }

  default List<Dict> parseColonMode(String dictTypeCode, String param) {
    String[] parts = StringUtils.split(param, COLON);
    return parseDetail(dictTypeCode, parts != null && parts.length > 1 ? parts[1] : "");
  }

  default List<Dict> parseNormalMode(String dictTypeCode, String param) {
    return parseDetail(dictTypeCode, param);
  }

  default List<Dict> parseDetail(String dictTypeCode, String param) {
    if (StringUtils.isBlank(param)) return Collections.emptyList();
    String[] array = param.split(REGULAR);
    AtomicInteger index = new AtomicInteger(0);
    return Stream.of(array)
        .filter(StringUtils::isNotBlank)
        .map(item -> parseItem(dictTypeCode, item, index))
        .filter(Objects::nonNull)
        .toList();
  }

  default Dict parseItem(String dictTypeCode, String item, AtomicInteger index) {
    String[] values = item.split(TEST);
    if (values.length == 2) {
      try {
        return new Dict(
            null,
            dictTypeCode,
            Integer.parseInt(values[0]),
            values[1],
            YesNo.YES.getCode(),
            LangHelper.get().storeLang(),
            index.incrementAndGet());
      } catch (NumberFormatException ex) {
        log.warn("DictDetail解析失败: {}, 内容: {}", ex.getMessage(), item);
      }
    }
    return null;
  }
}
